package com.yangye.pilog.aspect;

import com.alibaba.fastjson.JSONObject;
import com.yangye.picommon.utils.RequestHolder;
import com.yangye.picommon.utils.ThrowableUtil;
import com.yangye.pilog.domain.SysLog;
import com.yangye.pilog.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Page.Yang
 * @date 2019/4/3 0003
 */
@Aspect
@Component
public class WebLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired
    private SysLogService sysLogService;

    private long startTime;

    /**
     * 切面签名定义：
     *   两个..代表所有子目录，最后括号里的两个..代表所有参数
     */
    @Pointcut("execution(* com.yangye..controller..*.*(..))")
    public void logPointCut() {}

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        HttpServletRequest request = RequestHolder.getRequest();

        logger.info("请求地址: " + request.getRequestURL().toString());
        logger.info("HTTP METHOD: " + request.getMethod());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        logger.info("参数 : " + JSONObject.toJSONString(joinPoint.getArgs()));
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointCut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        startTime = System.currentTimeMillis();
        result = joinPoint.proceed();
        // 保存日志
        SysLog log = new SysLog();
        log.setType("INFO");
        log.setTime(System.currentTimeMillis() - startTime);
        sysLogService.saveLog(joinPoint, log);
        return result;
    }

    @AfterThrowing(pointcut = "logPointCut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        // 保存日志
        SysLog log = new SysLog();
        log.setType("ERROR");
        log.setTime(System.currentTimeMillis() - startTime);
        log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
        sysLogService.saveLog(joinPoint, log);

    }

    /**
     * returning的值和doAfterReturning的参数名一致
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容(返回值太复杂时，打印的是物理存储空间的地址)
        logger.debug("返回值 : " + ret);
    }
}
